<?php
/**
 * 名称：UserModel
 * 描述：用户模型
 * 作者：lan 时间：2013-05-02
 * 版本号：V1.0.0
 */
class UserModel extends Model {
	public static $nameHash = array();
	var $uid;
	
	/**
	 * 验证email输入的正确性
	 * @param unknown_type $email 邮箱
	 * @return boolean
	 */
	public function is_email($email) {
		return preg_match ( '/^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*@([_a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/', $email );
	}
	
	/**
	 * 验证email是否重复
	 * @param unknown_type $email 邮箱
	 * @param unknown_type $uid 用户Id
	 * @return array
	 */
	public function emailRepeat($email,$uid = 0) {
		$data ['uid'] = array (
				'neq',
				$uid
		);
		$data['email'] = $email;
		return $this->where($data)->find();
	}
	
	/**
	 * 验证昵称输入的正确性
	 * @param unknown_type $uname
	 * @return boolean
	 */
	public function is_nickname($uname) {
		return preg_match("([a-z0-9[^A-Za-z0-9_\n\t]]*)",$uname);
	}
	
	/**
	 * 判断昵称是否重复
	 * @param unknown_type $uname 昵称
	 * @param unknown_type $uid 用户Id
	 * @return array
	 */
	public function unameRepeat($uname,$uid=0) {
		$data ['uid'] = array (
				'neq',
				$uid
		);
		$data['uname'] = array('eq',$uname);
		return $this->where($data)->find();
	}
	
	/**
	 * 判断域名是否重复
	 * @param unknown_type $domain 个性域名
	 * @param unknown_type $uid 用户Id
	 * @return array
	 */
	public function domainRepeat($domain,$uid=0) {
		$data ['uid'] = array (
				'neq',
				$uid
		);
		$data['domain'] = array('eq',$domain);
		return $this->where($data)->find();
	}
	
	/**
	 * 删除用户
	 * @param unknown_type $uids 用户id
	 * @return boolean
	 */
	public function deleteUser($uids) {
		set_time_limit(0);
	
		if ( empty($uids) ) return false;
		$map['uid'] = array('in', $uids);
// 		$map['admin_level'] = 0;
		$res = model('User')->where($map)->delete();
		unset($map['admin_level']);
		$res = true;
		if ($res) {
			//删除用户资料相关信息
			M('CreditUser')->where($map)->delete();
			M('Feed')->where($map)->delete();
			M('Invitecode')->where($map)->delete();
			model('InviteRecord')->where(array('uid'=>array('IN',$uids),'fid'=>array('IN',$uids),'_logic'=>'OR'))->delete();
			M('LoginRecord')->where($map)->delete();
			M('Notify')->where(array('from'=>array('IN',$uids),'receive'=>array('IN',$uids),'_logic'=>'OR'))->delete();
			M('UserOnline')->where($map)->delete();
			model('UserProfile')->where($map)->delete();
			M('UserVerified')->where($map)->delete();
			M('AdminLog')->where($map)->delete();
			M('CreditUser')->where($map)->delete();
			M('Denounce')->where($map)->delete();
			M('RoleUser')->where(array('user_id'=>array('IN',$uids)))->delete();
			M('Login')->where($map)->delete();
			M('Login_record')->where($map)->delete();
			model('Message')->where(array('from_uid'=>array('IN',$uids),'to_uid'=>array('IN',$uids),'_logic'=>'OR'))->delete();
			M('Message_content')->where(array('list_id'=>array('IN',$uids),'from_uid'=>array('IN',$uids),'_logic'=>'OR'))->delete();
			M('Message_list')->where(array('list_id'=>array('IN',$uids),'from_uid'=>array('IN',$uids),'_logic'=>'OR'))->delete();
			M('Message_member')->where(array('list_id'=>array('IN',$uids),'member_uid'=>array('IN',$uids),'_logic'=>'OR'))->delete();
			M('User_app')->where($map)->delete();
			M('User_blacklist')->where($map)->delete();
			M('User_count')->where($map)->delete();
			M('User_group_link')->where($map)->delete();
			M('User_online')->where($map)->delete();
			M('User_privacy')->where($map)->delete();
			M('User_profile')->where($map)->delete();
			M('User_tag')->where($map)->delete();
			M('User_verified')->where($map)->delete();
			M('Album')->where($map)->delete();
			M('Albumphoto_like')->where($map)->delete();
			M('Event')->where($map)->delete();
			M('Event_photo')->where($map)->delete();
			M('Event_user')->where($map)->delete();
			M('Space')->where($map)->delete();
			model('Weibo')->where($map)->delete();
			model('Atme')->where($map)->delete();
			model('Comment')->where($map)->delete();
			model('Favorite')->where($map)->delete();
			model('Follow')->where(array('uid'=>array('IN',$uids),'fid'=>array('IN',$uids),'_logic'=>'OR'))->delete();
			model('FollowGroup')->where(array('uid'=>array('IN',$uids),'follow_id'=>array('IN',$uids),'_logic'=>'OR'))->delete();
			M('Follow_group_link')->where($map)->delete();
			model('Star')->where($map)->delete();
			//删除用户附件
			$all_attach	=	M('Attach')->where(array('userId'=>array('IN',$uids)))->select();
			foreach($all_attach as $v){
				unlink(UPLOAD_PATH.'/'.$v['savepath'].$v['savename']);
			}
			$result = M('attach')->where(array('userId'=>array('IN',$uids)))->delete();
			if($result){
				echo 'delete succesful!';
			}
		}
		return $res;
	}
	
	/**
	 * 获取用户基本信息字段
	 * @param string $module 字段类别,contact联系的字段、inro基本介绍的字段
	 */
	protected function data_field($module = '',$space=false){
		if($space){
			$list = $this->table(C('DB_PREFIX').'user_set')->where("status=1 and showspace=1")->select();
		}else{
			$list = $this->table(C('DB_PREFIX').'user_set')->where("status=1")->select();
		}
		foreach ($list as $value){
			$data[$value['module']][$value['fieldkey']] = $value['fieldname'];
		}
		return ($module)?$data[$module]:$data;
	}
	
	/**
	 * 根据标示符(uid或uname或email或domain)获取用户信息
	 * 首先检查缓存(缓存ID: user_用户uid / user_用户uname), 然后查询数据库(并设置缓存).
	 * @param string|int $identifier      标示符内容
	 * @param string     $identifier_type 标示符类型. (uid, uname, email, domain之一)
	 */
	public function getUserByIdentifier($identifier, $identifier_type = 'uid'){
		if ($identifier_type == 'uid' && !is_numeric($identifier))
			return false;
		else if (!in_array($identifier_type, array('uid','uname','email','domain')))
			return false;
		$user = $this->getUserInfoCache($identifier, $identifier_type);
		return $user;
	}
	
	/**
	 * 缓存用户列表
	 * 缓存key的格式为: user_用户uid 和 user_用户昵称
	 * @param array $user_list 用户ID列表, 或者用户详情列表. 如果为用户ID列表时, 本方法会首先获取用户详情列表, 然后缓存.
	 * @return boolean true:缓存成功 false:缓存失败
	 */
	public function setUserObjectCache($user_list){
		if (!is_array($user_list))
			return false;
		if (!is_array($user_list[0]) && !is_numeric($user_list[0]))
			return false;
		if (is_numeric($user_list[0])) {
			foreach($user_list as $val) {
				$user = $this->getUserInfoCache($val);
			}
		} else {
			foreach($user_list as $val) {
				$this->getUserInfoCache($val['uid']);
			}
		}
		return true;
	}
	
	/**
	 * 获取用户基本信息缓存
	 * @param int $uid 用户UID，string $type 查询类型(uid,uname,email,domain)
	 * @return array 用户基本信息
	 */
	public function getUserInfoCache($uid, $type = 'uid') {
		//如果为空，则直接退出
		$defaultValue = $uid;
		if(empty($uid)) {
			return false;
		}
		if(!in_array($type, array('uid','uname','email','domain'))) {
			return false;
		}
		//获取用户的UID
		if(!is_numeric($uid) && $type != 'uid') {
			if(isset(self::$nameHash[$type][$defaultValue])){
				$uid = self::$nameHash[$type][$defaultValue];
			} else {
				$uid = $this->where("{$type}='{$defaultValue}'")->getField('uid');
				self::$nameHash[$type][$defaultValue] = $uid;
			}
			if(empty($uid)) {
				return false;
			}
		}
		//姓名
		if(($userInfo = S("userInfo_user_".$uid)) ===false){
			$userInfo = $this->where('uid='.$uid)->find();
			S("userInfo_user_".$uid,$userInfo);
		}
		//积分与经验
		$userCredit = service ( 'Credit' )->getUserCredit($uid);
		$userInfo['credit'] = $userCredit;
		//关注数
		//if(($userInfo['following'] = S("userInfo_following_".$uid)) ===false){
			$count['following'] = M('weibo_follow')->where("uid={$uid} AND type=0")->count();
			$userInfo['following'] = $count['following'];
			//S("userInfo_following_".$uid,$userInfo['following']);
		//}	
		//粉丝数
		//if(($userInfo['follower'] = S("userInfo_follower_".$uid)) ===false){
			$count['follower']  = M('weibo_follow')->where("fid={$uid} AND type=0")->count();
			$userInfo['follower'] = $count['follower'];
		//	S("userInfo_follower_".$uid,$userInfo['follower']);
		//}
		//微博数
		if(($userInfo['miniNum'] = S("userInfo_miniNum_".$uid)) ===false){
			$count['miniNum'] = M('weibo')->where("uid={$uid} AND isdel=0")->count();
			$userInfo['miniNum'] = $count['miniNum'];
			S("userInfo_miniNum_".$uid,$count['miniNum']);
		}
		//sun 修改 2013/8/26
		//个人简介信息
		if(($userInfo['summary'] = S("userInfo_summary_".$uid)) ===false){
			$count['summary'] = M('user_profile')->where("`uid`={$uid} AND type='summary'")->getField("data");
			$userInfo['summary'] = unserialize($count['summary']);
			S("userInfo_summary_".$uid,$userInfo['summary']);
		}
		//教育情况 数据结构：s:54:"school:湘南学院;;;year:2008;;;classes:计算机系";
		if(($userInfo['education'] = S("userInfo_education_".$uid)) ===false){
			$count['education'] = M('user_profile')->where("`uid`={$uid} AND module='education'")->getField("id,data");
			$school = '';
			$year = 0;
			foreach ($count['education'] as $value){
				$ary = split ( ";;;", unserialize($value) );
				$arrS = split ( ":", $ary [0] );
				$ary_1 = split ( ":", $ary [1] );
				if($year < intval($ary_1[1])){
					$year = intval($ary_1[1]);
					$school = $arrS[1]; 
				}
			}
			$userInfo['education'] = $school;
			S("userInfo_education_".$uid,$userInfo['education']);
		}
		//end
		return $userInfo;
	}
	
	/**
	 * 用户退出	
	 * M2
	 * @param
	 */
	public function userLogout() {
		// 注销session
		unset($_SESSION['mid']);
		unset($_SESSION['uname']);
		unset($_SESSION['userInfo']);
		unset($_SESSION['administrator']);
		unset($_SESSION[C('ADMIN_AUTH_KEY')]);
		session('rm',null);
		// 注销cookie
		setcookie('ylsnsemail', '',time()-3600*24*365,'/',C('COOKIE_DOMAIN'));
		setcookie('ylsnspassword', '',time()-3600*24*365,'/',C('COOKIE_DOMAIN'));
		setcookie('ylsnscookie', '',time()-3600*24*365,'/',C('COOKIE_DOMAIN'));
		setcookie("ylsnsmid",'',time()-3600*24*365,'/',C('COOKIE_DOMAIN'));
		setcookie("i8userid",'',time()-3600*24*365,'/',C('COOKIE_DOMAIN'));
		setcookie("i8username",'',time()-3600*24*365,'/',C('COOKIE_DOMAIN'));
		common('Url')->getSysOperUrl('synlogout');
	}
	
	/**
	 * 用户退出
	 * M2
	 * @param
	 */
	public function userSessionLogout() {
		// 注销session
		unset($_SESSION['mid']);
		unset($_SESSION['uname']);
		unset($_SESSION['userInfo']);
		unset($_SESSION['administrator']);
		unset($_SESSION[C('ADMIN_AUTH_KEY')]);
		session('rm',null);
		// 注销cookie
		setcookie('ylsnsemail', '');
		setcookie('ylsnspassword', '');
		setcookie('ylsnscookie', '');
	}
	
	/**
	 * 获取用户昵称
	 * @param int $uid 用户ID
	 */
	public function getUserNmae($uid){
		$list = model('User')->where("uid=".$uid)->field("uname")->select();
		if(count($list)>0)
			return $list[0]["uname"];
		else
			return "";
	}
	
	/**
	 * 获取给定字符串中被@用户的uid数组
	 * M2
	 * @param string $content 待搜索的内容
	 * @return array 返回用户ID的数组
	 */
	public function getUids($content) {
		preg_match_all("/@(.+?)([\s|:]|$)/is", $content, $matches);
		$unames = $matches[1];
		$map['uname'] = array (
				'IN',
				$unames
		);
		$ulist = $this->where($map)->field('uid')->select();
		return common('Array')->getSubByKey($ulist, 'uid');
	}
	
	/**
	 * 记录登录信息
	 * @param int $uid 用户ID
	 */
	public function recordLogin($uid) {
		$data['uid']	= $uid;
		$data['ip']		= get_client_ip();
		$data['place']	= get_client_ip();//convert_ip($data['ip']);
		$data['ctime']	= time();
		M('login_record')->add($data);
	}
	
	/**
	 * * 用于搜索引擎 **
	 */
	/**
	 * 搜索用户
	 *
	 * @param string $key
	 *        	关键字
	 * @param integer $follow
	 *        	关注状态值
	 * @param integer $limit
	 *        	结果集数目，默认为100
	 * @param integer $max_id
	 *        	主键最大值
	 * @param string $type
	 *        	类型
	 * @param integer $noself
	 *        	搜索结果是否包含登录用户，默认为0
	 * @return array 用户列表数据
	 */
	public function searchUser($key = '', $follow = 1, $limit = 10, $max_id = '', $type = '', $noself = '0', $page, $atme) {
		$where = " (uname LIKE '%{$key}%')";
		// 过滤未激活和未审核的用户
		$where .= " AND is_active=1";
		if (! empty ( $max_id )) {
			$where .= " AND uid < " . intval ( $max_id );
		}
		if (! empty ( $noself )) {
			$where .= " AND uid !=" . intval ( $_SESSION['mid'] );
		}
		if ($follow == 1) {
			// 只选择我关注的人
			$where .= " AND uid IN (SELECT fid FROM " . $this->tablePrefix . "weibo_follow WHERE uid = '{$_SESSION['mid']}')";
		}
		// 未分页形式
		$list ['data'] = $this->where ( $where )->field ( 'uid,uname' )->limit ( $limit )->order ( 'uname ASC' )->select ();
		// 添加用户信息
		foreach ( $list ['data'] as $k => $v ) {
			$list ['data'][$k]['avatar_small'] = 'http://' . SITE_DOMAIN . common("Url") -> getUserFaceUrl($list ['data'][$k]['uid'],"s");
			$list ['data'][$k]['search_key'] = $list ['data'][$k]['uname'];
		}
		return $list;
	}
	
	/**
	 * 验证phone是否重复
	 * @param unknown_type $phone 手机号
	 * @param unknown_type $uid 用户Id
	 * @return array
	 */
	public function phoneRepeat($phone,$uid = 0) {
		$data ['uid'] = array (
				'neq',
				$uid
		);
		$data['phone'] = $phone;
		return $this->where($data)->find();
	}
}

?>
